package com.edu.servlet;

import com.edu.entity.userFollow;
import com.edu.service.myFollowService;
import com.edu.service.impl.myFollowServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/follow")
public class FollowServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    myFollowService mfs = new myFollowServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 核心功能：获取关注列表
        String userIdString = request.getParameter("userId");
        
        List<userFollow> follows = new ArrayList<userFollow>();
        
        try {
			int userId = Integer.parseInt(userIdString);
			follows = mfs.getfollows(userId);
		} catch (Exception e) {
			System.out.println("出错了"+e);
		}
        
        
        // 构建响应数据
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", follows);
        
        // 设置响应类型
        response.setContentType("application/json;charset=UTF-8");
        objectMapper.writeValue(response.getWriter(), result);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 核心功能：取消关注
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();
        
        String userIdString = request.getParameter("userId");
        int userId = Integer.parseInt(userIdString);
			
	
        String action = request.getParameter("action");
        
        if ("unfollow".equals(action)) {
            try {
                int followId = Integer.parseInt(request.getParameter("followId"));
                
                // 执行取消关注操作
                if (mfs.unfollowUser(userId, followId)) {
                    result.put("success", true);
                    result.put("message", "取消关注成功");
                } else {
                    result.put("success", false);
                    result.put("message", "取消关注失败");
                }
            } catch (NumberFormatException e) {
                result.put("success", false);
                result.put("message", "参数错误");
            }
        } else {
            result.put("success", false);
            result.put("message", "无效操作");
        }
        
        objectMapper.writeValue(response.getWriter(), result);
    }
}